package display;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Hashtable;

import javax.print.DocFlavor.INPUT_STREAM;

import com.lowagie.tools.split_pdf;

import type.Report;
import utility.CapitalChar;
import utility.ConvertToLower;
import utility.Input;

import query.condition.typereport.Typereport;
import query.view.Query;

import database.RecordSearch;
import dbmanager.ChekInMaster;
import dbmanager.Column;
import dbmanager.DBManager;
import dbmanager.GetIdName;
//import file.SearchRecord;

public class BuildFile implements Display 
{
	int ParentY;
	final String WIDTH="width";
	final String NEXTX ="nextx";
	final String NEXTY="nexty";
    final String X="x";
    String PATH="path";
    final String Y="y";
    final String TEXT="text";
    final String REPORT="printreport";
	String ReportId;
	DBManager Db;
	//SearchRecord Sr;
	RecordSearch ps;
	GetIdName gid ;	
	//String build_path=Input.CUSTOMREPORTS;
	Heading hd;
	String ReportName;
	String output_path="";
	//String input_path;
	String transId="";
	String table_name; 
	ChekInMaster checkMaster;
	String ALIGN="align";
	RandomAccessFile file_write ;
	String STORAGE="storage";
	String buffer[];
	
	public BuildFile(DBManager Db) 
	{
		this.Db = Db;
		//this.Db.getConnect();
		ps = new RecordSearch(Db);
		gid = new GetIdName(Db);
	}
	
	public BuildFile(String ReportName,String transId,DBManager Db)
	{
		this.Db = Db;
		checkMaster = new ChekInMaster(Db);
		this.ReportName = ReportName;
		gid = new GetIdName(Db);
		this.ReportId =gid.getId(ReportName);
		ps = new RecordSearch(Db);
		//getPath(ReportId,transId );		
		this.transId = transId;
		//input_path = getPath(ReportId,transId );
		//output_path =//input_path.replace(Input.FILRFORMAT,"")+"_view"+Input.FILRFORMAT+;
		//output_path =  input_path + "_view"+Input.FILRFORMAT;
		//input_path =  input_path +Input.FILRFORMAT;
		/*File delete = new File(output_path);
		if(delete.exists()==true)
			delete.delete();*/
	}
	
	public void setId(String ReportName,DBManager db)
	{
		this.Db = new DBManager();
		Db.getConnect();
		gid =new GetIdName(Db);
		this.ReportName = ReportName;
		ReportId = gid.getId(ReportName);		
		//input_path = getPath(ReportId,transId );
		Hashtable<Object, Object> table =new Hashtable<Object, Object>();
		output_path ="_view"+Input.FILRFORMAT;
		gid = new GetIdName(Db);
		ps = new RecordSearch(Db);
	/*	File delete = new File(output_path);
		if(delete.exists()==true)
			delete.delete();
		getPath(ReportId,transId );*/
   }
	public void run()
	{
		initializeData();
	}
	synchronized void writeTOFile()
	{
		Write_Heading();
		Write_File();
	}
	
	public void initializeData()
	{
		Hashtable<Object, Object>map = new  Hashtable<Object, Object>();
		if(output_path.length()==0)
		{	
			output_path = getPath(ReportId,transId)+Input.FILRFORMAT;
		}  
	    Hashtable<Object, Object> reportmap = new Hashtable<Object, Object>();
	    
	    String reportid= gid.getId("report");
		Hashtable<Object, Object> hasht = new Hashtable<Object, Object>();
		hasht.put("pid", reportid);
		hasht.put("mid", ReportId);
		hasht.put("td", "null");
		/*SearchRecord sr =new SearchRecord(Masterreport);
		sr.fileOpen();
		String result[] = sr.getRecordSet(hasht);
		sr.fileClose();*/
		
		ps = new RecordSearch(Db);
		ps.setConditionMap(hasht);
		String result[] = ps.getArrayFromResultSet();
		String reportname="";
		for(int i=0;i<result.length;i++)
		{
			String splitresult[] = result[i].split("\t");
			reportname = splitresult[Column.pv_index-1];
			if(reportname.equals("0"))
				reportname = splitresult[Column.vt_index-1];
		}
		
    	reportmap.put("report",gid.getItem(reportname));
    	reportmap.put("value", transId);
    	/*Query query =new Query();		
		query.setDbmanager(Db);
		query.setReportMap(reportmap);
		query.initializeData();
		query.getResult();
		buffer = query.getbuffer();*/
    	
    	Query query =new Query();		
		query.setDbmanager(Db);
		query.setReportMap(reportmap);
		query.initializeData();
		query.getResult();
		buffer =query.getbuffer();
		writeTOFile();
	
	    map.put("pid", gid.getId(REPORT));
	   // String ReportPath = Input.MASTERREPORTSPATH+"//"+ReportId+"//"+ReportId+"_mid"+Input.FILRFORMAT;
	    map.put("mid", ReportId);
	    map.put("td", "null");
	 	/*Sr = new SearchRecord(ReportPath);
	 	Sr.fileOpen();
	    String line[] =Sr.getRecordSet(map);
	    Sr.fileClose();*/
	    
	    ps = new RecordSearch(Db);
		ps.setConditionMap(map);
		String line[] = ps.getArrayFromResultSet();
	    for(int i=0;i<line.length;i++)
	    {
	    	String Split[]=line[i].split("\t");
	    	ReportId =Split[Column.pv_index-1];
	    	/*
	    	
	    	build_path = getPath(ReportId,transId) ;
	    	 input_path = build_path ;
	    	if(transId.length()==0)
	    		input_path =  Input.ROOT + build_path + ReportName + Input.FILRFORMAT;
	    	else
	    		input_path = Input.ROOT + build_path+ "_"+transId+Input.FILRFORMAT;*/
	    	
		
	    	initializeData();
	    }
	 }
	
	public String getPath(String ReportId,String tid)
	{
		String ReturnPath="";
		String reportname="";
		
			String reportid= gid.getId("report");
			Hashtable<Object, Object> hasht = new Hashtable<Object, Object>();
			hasht.put("pid", reportid);
			hasht.put("mid", ReportId);
			/*SearchRecord sr =new SearchRecord(Masterreport);
			sr.fileOpen();
			String result[] = sr.getRecordSet(hasht);
			sr.fileClose();*/
			
			ps = new RecordSearch(Db);
			ps.setConditionMap(hasht);
			hasht.put("td", "null");
			String result[] = ps.getArrayFromResultSet();
			for(int i=0;i<result.length;i++)
			{
				String splitresult[] = result[i].split("\t");
				reportname = splitresult[Column.pv_index-1];
				if(reportname.equals("0"))
					reportname = splitresult[Column.vt_index-1];
			}
			Hashtable<Object ,Object> map =new Hashtable<Object, Object>();
			map.put("mid", ReportId);
			map.put("pid", gid.getId(STORAGE));
			map.put("td", "null");
			ps.setConditionMap(map);
			map.clear();
			result = ps.getArrayFromResultSet();
		    for(int k=0;k<result.length;k++)
		    {
		    	String split[] = result[k].split("\t");
		    	map.clear();
		    	map.put("mid", split[Column.pv_index-1]);
				map.put("pid", gid.getId(PATH));
				map.put("td", "null");
				ps.setConditionMap(map);
				String temp[] = ps.getArrayFromResultSet();
				if(temp.length>0)
				{
					split = temp[0].split("\t");
					if(split[Column.pv_index].equals("0"))
						output_path = Input.ROOT + gid.getItem(split[Column.pv_index-1]);
					else
						output_path = Input.ROOT +split[Column.vt_index-1];
						
				}
		    }
		    Hashtable<Object, Object> newreportmap =new Hashtable<Object, Object>();
		    Report report =new Report(Db,reportname);
			String typereport = report.GettypeofReport(); 
			newreportmap = report.getReportMap();
			newreportmap = ConvertToLower.convertHashKey(newreportmap);
			try {
				Typereport type; 
				Class C = Class.forName("combinereport.condition.typereport."+CapitalChar.makeFirstCharCapital(typereport.trim()));
				type = (query.condition.typereport.Typereport )C.newInstance();
				type.setData("",tid, Db, newreportmap);
				output_path = type.getPath(gid.getItem(reportname));
				ReturnPath.replace(Input.FILRFORMAT, "");
				
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//return ReturnPath;
		    ReturnPath = Input.BILLREPORT +output_path + "//" +gid.getItem(ReportId)+tid;
		return ReturnPath;	
			
			/*String storage = gid.getId("Storage");
			String tempPath = Input.MASTERREPORTSPATH+reportname+"//"+reportname+"_mid"+Input.FILRFORMAT;
			RandomAccessFile file = new RandomAccessFile(tempPath,"r");
			hasht.put("pid", storage);
			sr =new SearchRecord(tempPath);
			sr.fileOpen();
			String line[] = sr.getRecordSet(hasht);
			sr.fileClose();
			for(int i=0;i<line.length;i++)
			{
				String split[] =line[i].split("\t");
				ReturnPath = split[Column.pv_index-1];
			}
			String Masterpath = Input.MASTERREPORTSPATH + ReturnPath + "//" + ReturnPath + "_mid" + Input.FILRFORMAT;
			sr.fileOpen();
			sr =new SearchRecord(Masterpath);
			sr.fileClose();
			 hasht.clear();
			 hasht.put("pid", gid.getId("path"));
			 String str[]= sr.getRecordSet(hasht);
			 for(int i=0;i<str.length;i++)
			 {
				 String split[] = str[i].split("\t");
				 ReturnPath= split[Column.pv_index-1];
				 if(ReturnPath.equals("0"))
					 ReturnPath = split[Column.vt_index-1];
				 else
					 ReturnPath=gid.getItem(ReturnPath);
			 }
			 file.close();
		 
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		//return ReturnPath +gid.getItem(reportname).toString().toLowerCase();*/
		/*Report report =new Report(Db,reportname);
		Hashtable<Object, Object> newreportmap =new Hashtable<Object, Object>();
		String typereport = report.GettypeofReport(); 
		newreportmap = report.getReportMap();
		newreportmap = ConvertToLower.convertHashKey(newreportmap);
		try {
			Typereport type; 
			Class C = Class.forName("combinereport.condition.typereport."+CapitalChar.makeFirstCharCapital(typereport.trim()));
			type = (combinereport.condition.typereport.Typereport )C.newInstance();
			type.setData("",Tranid, Db, newreportmap);
			ReturnPath = type.getPath(gid.getItem(reportname));
			ReturnPath.replace(Input.FILRFORMAT, "");
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ReturnPath; */
	}
	
	//------------------------------write heading in output file-----------------------------
	public void Write_Heading()
	{	
		 hd = new Heading(ReportId);
 		 try 
 		 {
			 //File file = new File("C://Reports//Custom_Reports//output.txt");
	 		 File file = new File(output_path);
	 		 file_write = new RandomAccessFile(file,"rws");	
	 		 file_write.seek(file_write.length());
		 	 
			 hd.get_Object();
			 System.out.println("The size of header vector "+hd.Heading_vector.size());
			 for(int i=0;i<hd.Heading_vector.size();i++)
			{
				System.out.println("heding is "+hd.Heading_vector.get(i).Result.get("text"));
				System.out.println("x "+hd.Heading_vector.get(i).Result.get(X).toString());
				System.out.println("y "+hd.Heading_vector.get(i).Result.get(Y).toString());
				
				String tempy=hd.Heading_vector.get(i).Result.get(Y).toString();
				
				int y=0;
				if(tempy.equals("null"))
				{
					tempy=hd.Heading_vector.get(i).Result.get(NEXTY).toString();
					if(!tempy.equals("null"))
					{
						try 
						{
							tempy =tempy.substring(tempy.indexOf("+")+1,tempy.length());
							y = ParentY + Integer.parseInt(tempy);
						} catch (NumberFormatException e) 
						{
							y=ParentY+1;
						}
					}
					else
					y=ParentY+2;
						
				}	
				else
				{
					if(tempy.indexOf("+")!=-1)
					{
						tempy =tempy.substring(tempy.indexOf("+")+1,tempy.length());
						try {
							y =ParentY + Integer.parseInt(tempy);
						} catch (NumberFormatException e) {
							y=ParentY+1;
						}
					}
					else
							y = Integer.parseInt(tempy);
				
				}	
				String width="";
				String align="";
				int Width;
				try 
				{
					width = hd.Heading_vector.get(i).Result.get(WIDTH).toString();
					align = hd.Heading_vector.get(i).Result.get(ALIGN).toString().toLowerCase();
					Width = Integer.parseInt(width);
				} 
				catch (Exception e) 
				{
					width = "null";
					align = "null" ;
					Width=0;
					//e.printStackTrace();
				}
				String string ="";
				String value =hd.Heading_vector.get(i).Result.get(TEXT).toString();
				if(!width.equals("null"))
				{
					
					if(Width<value.length())
						value = value.substring(0,Width);
					Width=Width-value.length();
					if(align.equals("left"))
					{
						for(int j=0;j<Width;j++)							
							string = string+"^";
						value = value + string;
					}	
					else
						if(align.equals("right"))
						{
							for(int j=0;j<Width;j++)
								string = "^"+string;
							value = string +value; 
						}
					else if(align.equals("center"))
					{
						for(int j=0;j<Width/2;j++)
								string = "^"+string;
						value = string+value;
						for(int j=Width/2;j<Width;j++)
							string = string+"^";
						value = value+string;
					}	
					//
				}	
				file_write.writeBytes(value +"\t");
				file_write.writeBytes(hd.Heading_vector.get(i).Result.get(X).toString()+"\t");
				file_write.writeBytes(String.valueOf(y));
				file_write.writeBytes("\n");
			}
		} 
		 catch (FileNotFoundException e)
		{
			 e.printStackTrace();
		} 
		 catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	
	//------------------------------write field into output file--------------------------- 
	public void Write_File()
	{
		RandomAccessFile file_reader;
		System.out.println("the build file is"+output_path);
		try
		{
			String line="";			
			try 
			{
				FiledList fl =new FiledList();
				fl.setId(ReportId,Db);
				fl.get_Object();
				
				
				int y=0, counter=1;
				String x = null;
				String ParentX = ""; 
				for(int kvar=1;kvar<buffer.length;kvar++)
				{
					line = buffer[kvar];
					try
					{
						if(line.contains("\t")==false)
							continue;
						String SubString[] = line.split("\t");
						if(counter==1)
						{
							for(int i=0;i<fl.field_vector.size();i++)
							{
								try
								{
									x = fl.field_vector.get(i).Result.get(X).toString();
									if(x.equalsIgnoreCase("null"))
										x = ParentX; 
									String tempy= fl.field_vector.get(i).Result.get(Y).toString();
									
									if(tempy.equals("null"))
									{
										try 
										{
											tempy= fl.field_vector.get(i).Result.get(NEXTY).toString();
											tempy =tempy.substring(tempy.indexOf("+")+1,tempy.length());										
											y = ParentY + Integer.parseInt(tempy);
										} catch (Exception e) {
											y=ParentY+1;
										}
										//y=ParentY+2;
									}
									else
										y = Integer.parseInt(tempy);

								/*
									if(tempy.equals("null"))
									{	
										tempy= fl.field_vector.get(i).Result.get(NEXTY).toString();
										if(!tempy.equals("null"))
										{
											tempy =tempy.substring(tempy.indexOf("+")+1,tempy.length());										
											y = ParentY + Integer.parseInt(tempy);
										}
										else
											y=ParentY+2;
									}	
									else
									{
										if(tempy.indexOf("+")!=-1)
										{
											tempy =tempy.substring(tempy.indexOf("+")+1,tempy.length());
											y =ParentY + Integer.parseInt(tempy);
										} else
											try {
												y = Integer.parseInt(tempy);
											} catch (Exception e) {
												System.out.println(tempy);
												e.printStackTrace();
											}
									}
								*/ 
									String width="";
									String align="";
									try 
									{
										width = fl.field_vector.get(i).Result.get(WIDTH).toString();
										align = fl.field_vector.get(i).Result.get(ALIGN).toString().toLowerCase();
									} 
									catch (Exception e) 
									{
										width = "null";
										align = "null" ;
										//e.printStackTrace();
									}
									
									String value;
									try 
									{
										String valOftext =fl.field_vector.get(i).Result.get(TEXT).toString();
										String splitbuffer[] = buffer[0].split("\t");
										int index_text=-1;
										for(int k=0;k<splitbuffer.length;k++)
											if(valOftext.equalsIgnoreCase(splitbuffer[k]))
											{
												index_text = k+1;
												break;
											}	
										value = SubString[index_text-1] + " ";
										if(value.equalsIgnoreCase("null"))
											value = "";
									} 
									catch (Exception e1) 
									{
									  value = "";
									}
									
									if(width.equals("null")==false)
									{
										try
										{
											int Width = Integer.valueOf(width);
											String string ="";
											
											if(Width<value.length())
												value = value.substring(0,Width);
											Width=Width-value.length();
											if(align.equals("left"))
											{
												for(int j=0;j<Width;j++)							
													string = string+"^";
												value = value + string;
											}	
											else
												if(align.equals("right"))
												{
													for(int j=0;j<Width;j++)
														string = "^"+string;
													value = string +value; 
												}
											else if(align.equals("center"))
											{
												for(int j=0;j<Width/2;j++)
														string = "^"+string;
												value = string+value;
												for(int j=Width/2;j<Width;j++)
													string = string+"^";
												value = value+string;
											}
											System.out.println("value:-"+value);
											ParentX = x + Width;
										}
										catch (Exception e) {
											//e.printStackTrace();
										}
									}
									else
										ParentX = x;
									if(value.contains("null"))
										value  =value.replace("null", "");
								
									file_write.writeBytes(value+"\t");
									file_write.writeBytes(x);
									file_write.writeBytes("\t");
									file_write.writeBytes(String.valueOf(y));
									file_write.writeBytes("\n");
								}
								catch (RuntimeException e) 
								{
									e.printStackTrace();
								}
							}
							//System.out.println(fl.field_vector.get(0).Result);
							counter++;
						}
						else
						{
							String nextx=null,nexty=null;
							for(int i=0;i<fl.field_vector.size();i++)
							{
								try
								{
									nextx = fl.field_vector.get(i).Result.get(NEXTX).toString();
									nexty = fl.field_vector.get(i).Result.get(NEXTY).toString();
									String width="";
									String align="";
									try
									{
										width = fl.field_vector.get(i).Result.get(WIDTH).toString();
										align = fl.field_vector.get(i).Result.get(ALIGN).toString().toLowerCase();
									}
									catch (Exception e) 
									{
										width = "null";
										align = "null";
									}
									x = (fl.field_vector.get(i).Result.get(X).toString());
									String tempy= fl.field_vector.get(i).Result.get(Y).toString();
									
									if(tempy.equals("null"))
									{
										try 
										{
											tempy= fl.field_vector.get(i).Result.get(NEXTY).toString();
											tempy =tempy.substring(tempy.indexOf("+")+1,tempy.length());										
											y = ParentY + Integer.parseInt(tempy);
										} catch (Exception e) {
											y=ParentY+1;
										}
										//y=ParentY+2;
									}
									else
										y = Integer.parseInt(tempy);
								/*
									if(tempy.equals("null"))
									{	
										tempy= fl.field_vector.get(i).Result.get(NEXTY).toString();
										if(!tempy.equals("null"))
										{
											tempy =tempy.substring(tempy.indexOf("+")+1,tempy.length());										
											y = ParentY + Integer.parseInt(tempy);
										}
										else
											y=ParentY+2;
									}	
									else
									{	
										if(tempy.indexOf("+")!=-1)
										{
											tempy =tempy.substring(tempy.indexOf("+")+1,tempy.length());
											y =ParentY + Integer.parseInt(tempy);
										}
										else
												y = Integer.parseInt(tempy);
									} 
									*/
									if(!nextx.equals("null"))
									{
										x = x+ Split_string(nextx, '+');
										fl.field_vector.get(i).Result.put(X, x);
									}
									if(!nexty.equals("null"))
									{
										y = y+ Split_string(nexty,'+');
										fl.field_vector.get(i).Result.put(Y, y);
									}
									String valOftext;
									String value;
									try 
									{
										valOftext = fl.field_vector.get(i).Result.get(TEXT).toString();
										String splitbuffer[] = buffer[0].split("\t");
										int index_text=-1;
										for(int k=0;k<splitbuffer.length;k++)
											if(valOftext.equalsIgnoreCase(splitbuffer[k])) 
												index_text = k+1;
										value = SubString[index_text-1]+" ";
										if(value.equalsIgnoreCase("null"))
											value = "";
										
									} catch (Exception e1) {
										value = "";
									}
									if(!width.equals("null"))
									{
										try
										{
											int Width = Integer.valueOf(width);
											if(Width<value.length())
												value = value.substring(0,Width);
											Width = Width- value.length();
											String string ="";
											if(align.equals("left"))
											{
												for(int j=0;j<Width;j++)							
													string = string+"^";
												value = value + string;
											}	
											else
												if(align.equals("right"))
												{
													for(int j=0;j<Width;j++)
														string = "^"+string;
													value = string +value; 
												}
											else if(align.equals("center"))
											{
												for(int j=0;j<Width/2;j++)
														string = "^"+string;
												value = string+value;
												for(int j=Width/2;j<Width;j++)
													string = string+"^";
												value = value+string;
											}
										}	
										catch (Exception e) {
											e.printStackTrace();
										}
									}
									if(value.contains("null"))
											value  =value.replace("null", "");
									file_write.writeBytes(value +"\t");							
									file_write.writeBytes(String.valueOf(x));
									file_write.writeBytes("\t");
									file_write.writeBytes(String.valueOf(y));
									file_write.writeBytes("\n");
								} 
								catch (Exception e) 
								{
									e.printStackTrace();
								}
							}
						}
					}
					catch (Exception e) {
						e.printStackTrace();
					}
					ParentY=y;
				}
				file_write.close();
			}
			catch (IOException e) 
			{
				e.printStackTrace();
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) 
	{
		//BuildFile bf = new BuildFile("ReportB");
		DBManager db= new DBManager();		
		db.getConnect();
		BuildFile bf = new BuildFile("Bill_Print_Report","4", db);
		bf.run();
	}
	
	public Hashtable<Object, Object> getObject() 
	{ 
		return null;
	}
	//----------------------Split string and return int value-----------------------
	public int Split_string(String str,char ch)
	{
		int index = str.indexOf(ch);
		str = str.substring(index+1);
		return Integer.parseInt(str);   
	}

	
}

